<template>
  <!--备机发放导入物流页面-->
  <panel title="物流信息录入">
    <el-form class="form-horizontal" :model="logisticsDto" :rules="logisticsRules" label-width="150px"
             ref="logisticsForm">
      <el-form-item label="发放日期" prop="backTime">
        <el-input v-model="formatterBackTime" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="传入文件" prop="fileUpload">
        <el-dropdown @command="handleCommand">
          <el-button type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <a href="/static/备机发放导入模板.xlsx" download="备机发放导入模板.xlsx"
               style="color:#5a5e66;text-decoration: none ">
              <el-dropdown-item command="handleDownload">模板下载
              </el-dropdown-item>
            </a>
            <el-dropdown-item command="handleImport">数据导入</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
      <el-form-item label="物流公司名称" prop="logisticsCompany">
        <el-select v-model="logisticsDto.logisticsCompany" placeholder="请选择物流公司"
                   prop="logisticsCompany" filterable="true" clearable="true">
          <el-option
            v-for="item1 in logisticsCompanyList"
            :key="item1.id"
            :label="item1.name"
            :value="item1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="快递单号" prop="logisticsNum">
        <el-input v-model="logisticsDto.logisticsNum" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="客户姓名">
        <el-input v-model="logisticsDto.customerName" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="客户地址">
        <el-input v-model="logisticsDto.customerAddress" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="客户联系电话">
        <el-input v-model="logisticsDto.customerTel" :disabled="true"></el-input>
      </el-form-item>
      <el-button type="primary" @click="onBtnDistributeWorkOrder()" style="float: right;">确认发放</el-button>
      <el-button type="primary" @click="onBtnReturn()" style="float: right; margin-right: 50px">返回</el-button>
    </el-form>

    <!-- 备机发放模板导入模态框 -->
    <el-dialog title="模板导入" :visible.sync="uploadVisible"
               :close-on-click-modal="false" :before-close="uploadCancel">
      <div>
        <el-form label-width="80px" ref="uploadForm" :inline="true">
          <el-form-item style="padding-left: 120px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="myHeaders"
              name="file"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload"
              multiple
              drag
              :limit="1"
              :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
          <!--显示导入中错误的数据-->
          <div style="height: 200px;overflow-y: auto" v-if="hideTable">
            <custom-table
              :data="wrongDataList"
              :columns="detailColumns">
            </custom-table>
          </div>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="uploadCancel()">取消</el-button>
        <el-button type="primary" @click="uploadConfirm()">确定</el-button>
      </div>
    </el-dialog>
  </panel>
</template>

<script>
  import Panel from '@/components/common/Panel'
  import {parseTime} from '@/utils'
  import {apiGetLogisticsCompanyList} from '@/api/dictionary'
  import {apiSpareDistribute} from '@/api/standby/index'
  import store from '@/store'
  import router from '@/router/index'
  import {apiGetReceiver} from '@/api/basic/info/inside/office'
  import {getUserId, getName} from '@/utils/token'
  import {baseInfo} from '@/utils/fetch'
  import {apiSpareDistributeReadExcel} from '@/api/excel/excelRead'
  import CustomTable from '@/components/table/CustomTable'

  export default {
    components: {
      Panel,
      CustomTable
    },
    computed: {
      formatterBackTime () {
        return parseTime(this.logisticsDto.backDay, '{y}-{m}-{d}')
      }
    },
    created () {
      this.apiGetReceiver()
      this.selectedLogisticsCompanyInit()
    },

    data () {
      return {
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        customer: {
          id: undefined,
          name: '',
          address: '',
          tel: ''
        },
        hideTable: false,
        logisticsCompanyList: [],
        logisticsDto: {
          id: null,
          backDay: new Date().getTime(),
          logisticsNum: '',
          logisticsCompany: '',
          customerName: '',
          customerAddress: '',
          customerTel: '',
          issuerId: '',
          issuerName: '',
          applicationId: '',
          filePath: '',
          applicationNum: '',
          modelName: ''
        },
        wrongDataList: [],
        uploadVisible: false,
        path: '',
        tableData: [],
        tableHeader: [],
        spareDistributeDto: {
          provinceCode: ''
        },
        detailColumns: [
          {label: '错误行号', name: 'wrongRowNO', width: '100', align: 'center'},
          {label: '错误原因', name: 'reason', width: '150', align: 'center'},
          {label: '型号', name: 'model', width: '100', align: 'center'},
          {label: 'SN号', name: 'ystsn', width: '150', align: 'center'}
        ],
        logisticsRules: {
          logisticsNum: [
            {required: true, message: '请填写快递单号', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          logisticsCompany: [
            {required: true, message: '请选择物流公司', trigger: 'change'}
          ],
          fileUpload: [
            {
              validator: (rule, value, callback) => {
                if (this.flagList.length === 0) {
                  callback(new Error('请传入excel文件'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ]
        },
        flagList: []
      }
    },
    methods: {
      handleCommand (command) {
        if (command === 'handleImport') {
          this.dialogType = 'upload'
          this.uploadVisible = true
        } else if (command === 'handleDownload') {
        }
      },
      uploadCancel () {
        this.uploadVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.flagList = []
        this.$refs['uploadForm'].resetFields()
      },
      uploadConfirm () {
        if (this.flagList !== undefined && this.flagList.length > 0) {
          if (this.wrongDataList.length > 0) {
            this.$message({
              showClose: true,
              message: '导入文件错误',
              type: 'error'
            })
            return
          } else {
            this.uploadVisible = false
            this.wrongDataList = []
            this.fileList = []
            this.hideTable = false
            this.$refs['uploadForm'].resetFields()
          }
        } else {
          this.$message({
            showClose: true,
            message: '未导入文件',
            type: 'error'
          })
          return
        }
      },
      selectedLogisticsCompanyInit () {
        apiGetLogisticsCompanyList().then(response => {
          let logisticsCompanyList = response.data
          let logisticsCompany = []
          let temp = {}
          for (let i in logisticsCompanyList) {
            if (!temp[logisticsCompanyList[i].name]) {
              temp[logisticsCompanyList[i].name] = logisticsCompanyList[i].id
            }
          }
          for (let k in temp) {
            logisticsCompany.push({'name': k, 'id': temp[k]})
          }
          this.logisticsCompanyList = logisticsCompany
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      apiGetReceiver () {
        this.spareDistributeDto.provinceCode = this.$route.query.provinceCode
        apiGetReceiver(this.spareDistributeDto).then(response => {
          this.logisticsDto.customerName = response.data[0].logisticsContact
          this.logisticsDto.customerTel = response.data[0].logisticsTel
          this.logisticsDto.customerAddress = response.data[0].logisticsAddr
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 上传成功后的回调
      uploadSuccess (response, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传文件成功',
          type: 'success'
        })
        this.logisticsDto.filePath = response.data
        let listQuery = {
          filePath: response.data,
          modelName: this.$route.query.mName,
          applicationId: this.$route.query.id
        }
        this.excelRead(listQuery)
        this.flagList = fileList
      },
      excelRead (listQuery) {
        apiSpareDistributeReadExcel(listQuery).then(response => {
          if (response.data) {
            if (response.data[0].wrongRowNO) {
              this.wrongDataList = response.data
              this.hideTable = true
            } else {
              this.$message({
                showClose: true,
                message: '导入执行中，请稍后',
                type: 'success'
              })
              this.wrongDataList = []
              this.hideTable = false
            }
          }
          this.fileList = []
        })
      },
      onBtnDistributeWorkOrder () {
        this.$refs['logisticsForm'].validate((valid) => {
          if (valid) {
            this.logisticsDto.applicationId = this.$route.query.id
            this.logisticsDto.issuerId = getUserId()
            this.logisticsDto.issuerName = getName()
            this.logisticsDto.modelName = this.$route.query.mName
            if (this.$route.query.status === '欠单') {
              this.logisticsDto.applicationNum = this.$route.query.accommodationNum
            } else if (this.$route.query.status === '未发放') {
              this.logisticsDto.applicationNum = this.$route.query.applicationNum
            } else if (this.$route.query.status === '全部发放') {
              this.logisticsDto.applicationNum = '0'
            }
            apiSpareDistribute(this.logisticsDto).then(() => {
              this.$message({
                showClose: true,
                message: '提交成功',
                type: 'success'
              })
              router.go(-1)
            })
          } else {
            return false
          }
        })
      },
      uploadError () {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
      },
      beforeAvatarUpload (file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }

        return extension && isLt2M
      },
      selected (data) {
        this.tableData = data.results
        this.tableHeader = data.header
      },
      handleRemove (file, fileList) {
        this.$message({
          message: '移除成功',
          type: 'success'
        })
        this.flagList = fileList
      },
      onBtnReturn () {
        // 物流信息录入界面
        router.go(-1)
      }
    }
  }
</script>
